package sample;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ：刘天予
 * @date ：Created in 2020/5/18 10:10
 * @description：
 * @modified By：
 * @version: $
 */
public class FileTask extends ScheduledService {

    private final static List<String> fileType = Arrays.asList("rar", "zip", "7z", "CAB", "ARJ", "LZH", "TAR", "GZ", "ACE", "UUE", "BZ2", "JAR", "ISO", "doc", "docx", "pdf");

    private String searchPath;

    private String searchName;

    private ObservableList<File> files = FXCollections.observableArrayList();

    public void init(String searchPath, String searchName) {
        this.searchName = searchName;
        this.searchPath = searchPath;
    }

    @Override
    protected Task<ObservableList<File>> createTask() {
        Task<ObservableList<File>> task = new Task<ObservableList<File>>() {
            @Override
            protected ObservableList<File> call() throws Exception {
                files = FXCollections.observableArrayList();
                searchFile(searchPath, searchName);
                return files;
            }
        };
        return task;
    }

    public void searchFile(String searchPath, String searchName) {
        java.io.File[] ls = FileUtil.ls(searchPath);
        for (java.io.File file : ls) {
            if (FileUtil.isDirectory(file))
                searchFile(file.getPath(), searchName);
            else if (file.getName().contains(searchName)) {
                if (fileType.contains(FileTypeUtil.getType(file).toUpperCase()) || fileType.contains(FileTypeUtil.getType(file).toLowerCase())) {
                    File f = new File();
                    f.setFileName(file.getName());
                    f.setFilePath(file.getPath());
                    files.add(f);
                }
            }
        }
    }

}
